package com.pilipili.zeus.eduService.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.pilipili.zeus.eduService.entity.EduComment;
import com.pilipili.zeus.eduService.entity.comment.CommentNode;
import com.pilipili.zeus.eduService.mapper.EduCommentMapper;
import com.pilipili.zeus.eduService.service.EduCommentService;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 评论 服务实现类
 *
 * @author Unlimited_Blade_Works
 * @since 2021-06-03
 */
@Service
public class EduCommentServiceImpl extends ServiceImpl<EduCommentMapper, EduComment> implements EduCommentService {
    @Override
    public List<CommentNode> getCommentTree() {
        List<EduComment> entities = list();
        //将获取的eduSubject对象数组封装成SubjectNode对象数组
        // BeanUtils.copyProperties:Bean对象的复制和储存
        //collect(Collectors.toList()):实例化对象，填充和合并多个中间结果，以保持可变数据结构的隔离
        List<CommentNode> commentNodes = entities.stream().map(eduComment -> {
            CommentNode commentNode = new CommentNode();
            BeanUtils.copyProperties(eduComment, commentNode);
            return commentNode;
        }).collect(Collectors.toList());

        //filter取得所有parentId为0的数据,也就是一级目录
        //map取得一级目录的下级目录的数据
        List<CommentNode> list = commentNodes.stream().filter(commentNode -> "0".equals(commentNode.getReplyId())).map((menu) -> {
            menu.setChildren(getCommentChildrenData(menu, commentNodes));
            return menu;
        }).collect(Collectors.toList());
        return list;
    }
    private List<CommentNode> getCommentChildrenData(CommentNode root,List<CommentNode> lists){
        List<CommentNode> children = lists.stream().filter(commentNode -> commentNode.getReplyId().equals(root.getId())
        ).map(commentNode -> {
            commentNode.setChildren(getCommentChildrenData(commentNode, lists));
            return commentNode;
        }).collect(Collectors.toList());
        return children;
    }

    @Override
    public Map<String, Object> getCommentInfo(Page<EduComment> pageParam, String courseId) {
        QueryWrapper<EduComment> wrapper = new QueryWrapper<>();
//        wrapper.orderByDesc("gmt_modified");
        wrapper.eq("course_id",courseId);

        baseMapper.selectPage(pageParam,wrapper);
        List<EduComment> commentList = pageParam.getRecords();

        Map<String, Object> map = new HashMap<>(20);
        map.put("items", commentList);
        map.put("current", pageParam.getCurrent());
        map.put("pages", pageParam.getPages());
        map.put("size", pageParam.getSize());
        map.put("total", pageParam.getTotal());
        return map;
    }


}
